﻿using LinkingCloud.API.Common.Helper;
using CoreFtp;
using CoreFtp.Enum;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace LinkingCloud.API.Common.FTP
{
    public class FtpHelper : IFtpHelper
    {
        private readonly FtpHelperSetting ftpHelperSetting;
        private readonly IFtpClient ftpClient;
        public FtpHelper()
        {
            ftpHelperSetting = Appsettings.GetSectionObject<FtpHelperSetting>("AppSettings:FtpHelperSetting");
            ftpClient = new FtpClient(new FtpClientConfiguration
            {
                Host = ftpHelperSetting.Host,
                Username = ftpHelperSetting.User,
                Password = ftpHelperSetting.Password,
                Port = ftpHelperSetting.Port,
                EncryptionType = FtpEncryption.Implicit,
                IgnoreCertificateErrors = true
            });
        }
        /// <summary>
        /// 从FTP/S server下载文件到本地
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        public async void FtpDownLoadFile(string filePath, string fileName)
        {
            var tempFile = new FileInfo(filePath);
            await ftpClient.LoginAsync();
            using (var ftpReadStream = await ftpClient.OpenFileReadStreamAsync(fileName))
            {
                using (var fileWriteStream = tempFile.OpenWrite())
                {
                    await ftpReadStream.CopyToAsync(fileWriteStream);
                }
            }
        }

        /// <summary>
        /// 上传文件到FTP
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        public async void FtpUpLoad(string filePath, string fileName, string folder = "")
        {
            try
            {
                var fileinfo = new FileInfo(filePath);
                await ftpClient.LoginAsync();
                if (!string.IsNullOrEmpty(folder)) 
                {
                    await ftpClient.ChangeWorkingDirectoryAsync(folder);
                }
                using (var writeStream = await ftpClient.OpenFileWriteStreamAsync(fileName))
                {
                    var fileReadStream = fileinfo.OpenRead();
                    await fileReadStream.CopyToAsync(writeStream);
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }


    }

    public class FtpHelperSetting
    {
        public string Host { get; set; }
        public int Port { get; set; }
        public string User { get; set; }
        public string Password { get; set; }
    }
}
